package uml.GUI;

import java.awt.Component;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JTabbedPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import uml.FileIO.FileHandler;
import uml.eventsystem.IObserver;
import uml.eventsystem.KeyHandler;
import uml.eventsystem.MouseHandler;
import uml.eventsystem.events.UMLEvent;
import uml.util.UMLConstants;

public class UMLTabbedPane
		extends JTabbedPane
		implements IObserver
{
	private static int m_numberOfDiagrams = 0;

	public UMLTabbedPane ()
	{
		setBackground (UMLConstants.TABBED_PANE_BACKGROUND);
		registerForEvents ();
	}

	private void registerForEvents ()
	{
		MouseHandler.getMouseHandler ().registerForAllUMLEvents (this);
	}

	@Override
	public void handleNotification (UMLEvent event)
	{

		switch (event.getEventId ())
		{
		case APPLICATION_EXIT:
		{
			System.exit (0);
		}
		case CREATE_DIAGRAM:
		{
			addTab ("New Diagram", new DiagramPanel ());
			this.setSelectedIndex (this.getComponentCount () - 1);
			validate ();
			break;
		}
		case CLOSE_DIAGRAM:
		{
			Component selectedDiagram = getSelectedComponent ();
			remove (selectedDiagram);
			validate ();
			break;
		}
		case OPEN:
		{
			final JFileChooser fc = new JFileChooser ();
			final FileNameExtensionFilter filter = new FileNameExtensionFilter ("ATeam Files", "ateam");
			fc.setFileFilter (filter);
			File file;

			int returnVal = fc.showOpenDialog (this);
			if (returnVal == JFileChooser.CANCEL_OPTION)
			{
				return;
			}
			else
			{
				file = fc.getSelectedFile ();
				DiagramPanel newPanel = new DiagramPanel();
				this.add(newPanel);
				FileHandler.open (file, newPanel);
				newPanel.setPath (file.getPath ());
				String name = file.getName ();
				String[] temp = name.split ("\\.");
				name = temp[0];
				addTab (name, newPanel);
				this.setSelectedIndex (this.getComponentCount () - 1);
				validate ();
			}
			break;
		}
		default:
		{
			Component selectedDiagram = getSelectedComponent ();
			if (selectedDiagram instanceof IObserver)
				((IObserver) selectedDiagram).handleNotification (event);
		}
		}
	}
}
